package bb.lanxing.common.engin.util;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

import com.garmin.fit.Mesg;
import com.garmin.fit.RecordMesg;
import com.garmin.fit.SessionMesg;
import bb.lanxing.App;
import bb.lanxing.calc.data.SourcePoint;
import bb.lanxing.common.config.Constants;
import bb.lanxing.device.sync.FitHelper;
import bb.lanxing.lib.devices.sync.FitManager;
import bb.lanxing.lib.devices.sync.FitTrans;
import bb.lanxing.model.WorkoutDatabaseHelper;
import bb.lanxing.model.database.Trackpoint;
import bb.lanxing.model.database.Workout;
import bb.lanxing.util.AppFileUtils;
import java.io.File;
import java.util.List;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class EnginUtil {
    private static final String ENGIN_FILE_DIR = "engin";
    private static final String SimulateGpsFile = "GpsSimulate.sml";
    private static final String TAG = "EnginUtil";
    private static final String WORKOUT_FILE_DIR = "workout";
    private static boolean isRecordOpen = false;
    private static boolean simulateLocation = false;

    public static String getEnginDir() {
        return AppFileUtils.buildExternalDirectoryPath(ENGIN_FILE_DIR);
    }

    public static void restartApp(Context context) {
        Intent launchIntentForPackage = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
        launchIntentForPackage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        ((AlarmManager) context.getSystemService(Context.ALARM_SERVICE))
                .set(AlarmManager.RTC, System.currentTimeMillis() + 200,
                        PendingIntent.getActivity(context.getApplicationContext(),
                                123456, launchIntentForPackage, Build.VERSION.SDK_INT >= 31 ?
                                        PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE : PendingIntent.FLAG_UPDATE_CURRENT));
        System.exit(0);
    }

    public static boolean isAPKDebugable(Context context) {
        try {
            return (context.getApplicationInfo().flags & 2) != 0;
        } catch (Exception e) {
            Log.w(TAG, "isAPKDebugable: ", e);
            return false;
        }
    }

    public static File getGpsSimulateFile() {
        return new File(AppFileUtils.buildExternalDirectoryPath(ENGIN_FILE_DIR), SimulateGpsFile);
    }

    public static Boolean isRecordOpen() {
        return isRecordOpen;
    }

    public static void setRecord(boolean z) {
        isRecordOpen = z;
    }

    public static boolean isSimulateLocation() {
        return simulateLocation;
    }

    public static void setSimulateLocation(boolean z) {
        simulateLocation = z;
    }

    public static void startWorkoutFileReCalc(Context context) {
        File file = new File(AppFileUtils.buildExternalDirectoryPath(ENGIN_FILE_DIR, WORKOUT_FILE_DIR));
        if (file.list() == null || file.list().length == 0) {
            Toast.makeText(context, "no workout file found !", Toast.LENGTH_SHORT).show();
            return;
        }
        WorkoutFileSimulator workoutFileSimulator = new WorkoutFileSimulator(file.getAbsolutePath());
        Toast.makeText(context, "workout file simulator started !", Toast.LENGTH_SHORT).show();
        workoutFileSimulator.startSimulator();
    }

    public static void startWorkoutRecordFromFit(String str, final Runnable runnable, final Runnable runnable2) {
        LocationRecorder.get().initRecord(true, false);
        FitManager fitManager = new FitManager(AppFileUtils.buildExternalDirectoryPath(Constants.FIT_DIR), new FitManager.FitManagerCallback() {
            @Override
            public void onFitReceived(FitTrans fitTrans) {
            }

            @Override
            public void onSport(FitTrans fitTrans, SessionMesg sessionMesg) {
            }

            @Override
            public void onMesg(FitTrans fitTrans, Mesg mesg) {
                if (mesg != null && mesg.getNum() == 20) {
                    SourcePoint createSourcePointByFitMesg = FitHelper.createSourcePointByFitMesg(new RecordMesg(mesg), 0);
                    if (!createSourcePointByFitMesg.hasGps()) {
                        return;
                    }
                    LocationRecorder.get().recordLocation(createSourcePointByFitMesg.getGpsPoint());
                } else if (mesg != null) {
                } else {
                    LocationRecorder.get().releaseRecord();
                    App.getContext().showMessage("生成文件成功");
                    Runnable runnable3 = runnable;
                    if (runnable3 == null) {
                        return;
                    }
                    runnable3.run();
                }
            }

            @Override
            public void onError(FitTrans fitTrans, Throwable th) {
                App.getContext().showMessage("生成文件失败");
                Runnable runnable3 = runnable2;
                if (runnable3 != null) {
                    runnable3.run();
                }
            }
        });
        FitTrans fitTrans = FitTrans.get();
        fitTrans.setPath(str);
        fitManager.decode(fitTrans);
    }

    public static void startWorkoutRecord(final long j, final Runnable runnable) {
        Observable.just(j).subscribeOn(Schedulers.io()).flatMap(new Func1<Long, Observable<Boolean>>() {
            @Override
            public Observable<Boolean> call(Long l) {
                Workout byServerId = Workout.getByServerId(l);
                boolean z = false;
                if (byServerId != null) {
                    if (Trackpoint.getCountByWorkout(byServerId.getId()) > 0) {
                        z = true;
                    }
                    return Observable.just(z);
                }
                return Observable.just(false);
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean bool) {
                if (bool) {
                    App.getContext().showMessage("开始生成位置记录文件");
                    List<Trackpoint> queryTrackPoint = WorkoutDatabaseHelper.queryTrackPoint(Workout.getByServerId(j).getId());
                    LocationRecorder.get().initRecord(true, false);
                    for (Trackpoint trackpoint : queryTrackPoint) {
                        LocationRecorder.get().recordLocation(trackpoint);
                    }
                    LocationRecorder.get().releaseRecord();
                    App.getContext().showMessage("生成位置记录文件成功");
                } else {
                    App.getContext().showMessage("未找到轨迹或没有下载点");
                }
                Runnable runnable2 = runnable;
                if (runnable2 != null) {
                    runnable2.run();
                }
            }
        });
    }

    public static void startWorkoutFileReCalc(final long j, final Runnable runnable) {
        Observable.just(j).subscribeOn(Schedulers.io()).flatMap(new Func1<Long, Observable<Boolean>>() {
            @Override
            public Observable<Boolean> call(Long l) {
                Workout byServerId = Workout.getByServerId(l);
                boolean z = false;
                if (byServerId != null) {
                    if (Trackpoint.getCountByWorkout(byServerId.getId()) > 0) {
                        z = true;
                    }
                    return Observable.just(z);
                }
                return Observable.just(false);
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean bool) {
                if (bool) {
                    WorkoutSimulator.setWorkoutServerId(j);
                    WorkoutSimulator.getInstance().setFinishCallback(new Runnable() {
                        @Override
                        public void run() {
                            if (runnable != null) {
                                runnable.run();
                            }
                            WorkoutSimulator.release();
                        }
                    });
                    WorkoutSimulator.getInstance().startSimulator();
                    App.getContext().showMessage("开始计算");
                    return;
                }
                App.getContext().showMessage("未找到轨迹或没有下载点");
            }
        });
    }
}
